<?php

namespace App\Services;

use App\Common\Sms\Sms;
use App\Models\User;
use Tymon\JWTAuth\Facades\JWTAuth;
use Overtrue\Socialite\SocialiteManager;

/**
 * 登录服务
 * Class LoginService
 * @package App\Services
 */
class LoginService extends BaseService
{
    /**
     * 小程序授权手机号登录
     */
    public function loginByOauth()
    {
        $code = request()->input('code', '');
        $iv = request()->input('iv');
        $encryptedData = request()->input('encryptedData');

        if(!$code || !$iv || !$encryptedData){
            $this->error(-100, '参数错误');
        }

        $app = WechatService::miniprogram();
        $session = $app->auth->session($code);
        info($session);
        if (!$session || $session['errcode']) {
            error(-100,  $session['errmsg']);
        }
        $openId = $session['openid'];
        if ($iv && $encryptedData) {
            $decryptedData = $app->encryptor->decryptData($session['session_key'], $iv, $encryptedData);
            $phoneNumber = $decryptedData['phoneNumber'];
        } else {
            $phoneNumber = '';
        }
        $user = User::whereMobile($phoneNumber)->first();
        if(!$user){
            //登录时，没有账号则创建
            $user = UserService::addUser([
                'wxapp_openid' => $openId,
                'mobile' => $phoneNumber
            ]);
        }
        $user->wxapp_openid = $openId;
        $user->save();
        $token = JWTAuth::fromUser($user);
        return $this->success(['token' => $token, 'userInfo' => $user]);
    }

    /**
     * 手机号验证码登录
     */
    public function loginByMobileCode()
    {
        $code = request()->input('code', '');
        $mobile = request()->input('mobile', '');
        $verifyCode =  request()->input('verify_code', '');

        if(!$mobile || !$verifyCode){
            return $this->error(-100, '参数错误');
        }

        $result = Sms::checkAuthCode($verifyCode, 'login', $mobile);
        if(is_error($result)){
            $this->error($result['errno'],  $result['message']);
        }

        if($code){
            $app = WechatService::miniprogram();
            $session = $app->auth->session($code);
            if (!$session || $session['errcode']) {
                return $this->error(-100,  $session['errmsg']);
            }
            $openId = $session['openid'];
        }
        $user = User::whereMobile($mobile)->first();
        if(!$user){
            //登录时，没有账号则创建
            $user = UserService::addUser([
                'wxapp_openid' => $openId,
                'mobile' => $mobile
            ]);
        }
        $user->wxapp_openid = $openId;
        $user->save();
        $token = JWTAuth::fromUser($user);
        return $this->success(['token' => $token, 'userInfo' => $user]);
    }

    /**
     * 小程序进入时登录
     */
    public function quietlyLogin()
    {
        $code = request()->input('code', '');

        if(!$code){
            return error(-1, '登录出错，请稍后重试');
        }
        $app = WechatService::miniprogram();
        $session = $app->auth->session($code);
        if (!$session || $session['errcode']) {
            $this->error(-1,  $session['errmsg']);
        }

        $openId = $session['openid'];
        //判断是否有此用户信息
        $user = User::whereWxappOpenid($openId)->first();
        if($user){
            $token = JWTAuth::fromUser($user);
            return $this->success(['token' => $token, 'userInfo' => $user]) ;
        }else{
            return $this->success();
        }
    }

    /**
     * app 授权登录
     */
    public function loginByOauth2()
    {
        $code = request()->input('code', '');

        $openPlatform = ConfigService::getSysValueByType(31);
        $config = [
            'wechat' => [
                'client_id'     => $openPlatform['appid'],
                'client_secret' => $openPlatform['appsecret'],
                'redirect'      => null,
            ],
        ];
        $socialite = new SocialiteManager($config);
        $wechat = $socialite->driver('wechat');
        $accessToken = $wechat->getAccessToken($code);
        $openId = $accessToken['openid'];

        //判断是否有此用户信息
        $user = User::whereOpenid($openId)->first();
        if(!$user){
            //登录时，没有账号则创建
            $user = UserService::addUser([
                'openid' => $openId,
                'unionid' => $accessToken['unionid'],
                'mobile' => '',
            ]);
        }
        $token = JWTAuth::fromUser($user);
        return $this->success(['token' => $token, 'userInfo' => $user]);
    }
}